/*
 * @Author: your name
 * @Date: 2024-05-05 15:07:37
 * @LastEditTime: 2024-05-05 15:26:22
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\669.修剪二叉搜索树.cpp
 */
/*
 * @lc app=leetcode.cn id=669 lang=cpp
 *
 * [669] 修剪二叉搜索树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        // 停止条件
        if(root == nullptr) return root;
        // 单层递归逻辑
        if(root->val < low){
            // 本节点需要去除，从本节点的右子树寻找头结点
            TreeNode* right = trimBST(root->right, low, high);
            return right;
        } 
        if(root->val > high){
            TreeNode* left = trimBST(root->left, low, high);
            return left;
        }
        root->left = trimBST(root->left, low, high);
        root->right = trimBST(root->right, low, high);
        return root;
    }
};
// @lc code=end

